package com.smartstate.EnvironmentMonitor.exception;


import com.smartstate.EnvironmentMonitor.vo.ResultCode;
import com.smartstate.EnvironmentMonitor.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;
import org.yaml.snakeyaml.constructor.DuplicateKeyException;

import javax.servlet.ServletException;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.util.List;

@RestControllerAdvice
@Slf4j
public class MyGlobalExceptionHandler {

    @ExceptionHandler(ServletException.class)
    public ResultVO handleServletException(Exception e) {
        log.error(e.getMessage(), e);
        return ResultVO.fail(9999, e.getMessage() + "\n" + e.getStackTrace());
    }

    @ExceptionHandler(value = CommonException.class)
    public ResultVO defaultErrorHandler(CommonException e) {
        log.error(e.getMessage(), e);
        return ResultVO.fail(e.code, e.getMessage());
    }

    /**
     * 打印关键log信息
     */
    private void createLogger(Exception e) {
        log.error(e.getMessage());
        log.error(e.getStackTrace()[0].toString());
        for (StackTraceElement stackTraceElement : e.getStackTrace()) {
            log.error(stackTraceElement.toString());
        }
    }

    @ExceptionHandler(NoHandlerFoundException.class)
    public ResultVO handlerNoFoundException(NoHandlerFoundException e) {
        log.error(e.getMessage(), e);
        return ResultVO.fail(404, "路径不存在，请检查路径是否正确");
    }

    @ExceptionHandler(DuplicateKeyException.class)
    public ResultVO handleDuplicateKeyException(DuplicateKeyException e) {
        String message = e.getCause().getMessage().replaceAll("(Duplicate entry ')|(' for key ')+(.)*","");
        return ResultVO.fail(ResultCode.RESOURCE_EXISTS.getCode(), message);
    }

    @ExceptionHandler(NullPointerException.class)
    public ResultVO handleNullPointerException(NullPointerException e) {
        log.error(e.getMessage(), e);
        return ResultVO.fail(ResultCode.RESOURCE_NOT_EXISTS.getCode(), ResultCode.RESOURCE_NOT_EXISTS.getMessage());
    }


    /**
     * post 提交 json 请求体校验
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResultVO handleValidation(MethodArgumentNotValidException e) {
        log.error(e.getMessage(), e);
        BindingResult exceptions = e.getBindingResult();
        if (exceptions.hasErrors()) {
            List<ObjectError> errors = exceptions.getAllErrors();
            if (!errors.isEmpty()) {
                FieldError fieldError = (FieldError) errors.get(0);
                return ResultVO.fail(fieldError.getDefaultMessage());
            }
        }
        return ResultVO.fail(2501, "请求参数有误");
    }

    /**
     * get or post 表单单个参数校验错误
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public ResultVO handleValidation(ConstraintViolationException e) {
        StringBuffer sb = new StringBuffer();
        for (ConstraintViolation<?> violation : e.getConstraintViolations()) {
            sb.append(violation.getMessage());
        }
        return ResultVO.fail(2501, sb.toString());
    }


    /**
     * get or post 表单提交转对象，校验对象错误
     */
    @ExceptionHandler(BindException.class)
    public ResultVO handleValidation(BindException e) {
        for (ObjectError error : e.getBindingResult().getAllErrors()) {
            return ResultVO.fail(error.getDefaultMessage());
        }
        return ResultVO.fail(2501, "请求参数有误");
    }

    @ExceptionHandler(value = RuntimeException.class)
    public ResultVO defaultErrorHandler(RuntimeException e) {
        log.error(e.getMessage(), e);
        return ResultVO.fail(ResultCode.Runtime_Exception.getCode(), e.getMessage());
    }

    /**
     * 开发时抛给前段
     */
    @ExceptionHandler(Exception.class)
    public ResultVO handleException(Exception e) {
        log.error(e.getMessage(), e);
        return ResultVO.fail(9999, e.getMessage() + "\n" + e.getStackTrace());
    }
}
